package com.sun.asyncimporttask.controller;

import com.sun.asyncimporttask.dto.ImportResult;
import com.sun.asyncimporttask.dto.TaskInfo;
import com.sun.asyncimporttask.entity.ImportTask;
import com.sun.asyncimporttask.mapper.ImportTaskMapper;
import com.sun.asyncimporttask.service.ImportService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 导入控制器
 */
@RestController
@RequestMapping("/api/import")
@RequiredArgsConstructor
public class ImportController {
    private final ImportService importService;

    @PostMapping("/users")
    public ResponseEntity<ImportResult> importUsers(@RequestParam("file") MultipartFile file) {
        String taskId = importService.asyncImport(file);
        return ResponseEntity.accepted().body(
                new ImportResult(taskId, "导入任务已提交")
        );
    }

    @GetMapping("/tasks/{taskId}")
    public ResponseEntity<TaskInfo> getTask(@PathVariable String taskId) {
        return ResponseEntity.ok(importService.getTaskInfo(taskId));
    }

    @GetMapping("/tasks")
    public ResponseEntity<List<TaskInfo>> listTasks() {
        return ResponseEntity.ok(importService.listTasks());
    }

    @GetMapping("/tasks/{taskId}/error-file")
    public ResponseEntity<Resource> downloadErrorFile(@PathVariable String taskId) {
        Resource resource = importService.getErrorFileResource(taskId);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}